﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MemoGame
{
    class Board
    {
        private int size;
        private SortedDictionary<string, Card> cards = new SortedDictionary<string, Card>();

        internal SortedDictionary<string, Card> Cards
        {
            get { return cards; }
            set { cards = value; }
        }

        public Card getField(string key)
        {
            if (cards.ContainsKey(key))
            {
                return cards[key];
            }
            return null;
        }

        public Board()
        {
        }

        public Boolean createBoard(int size)
        {
            //we can create board only with even number of elements
            if (size % 2 == 0)
            {
                this.size = size;
                //create cards
                List<Card> tempCards = new List<Card>();
                for (int i = 1; i <= size*size/2; i++)
                {
                    //each card appears exactly twice
                    for (int j = 0; j < 2; j++)
                    {
                        tempCards.Add(new Card(i));
                    }
                }
                //create char array containing an alphabet
                char[] az = Enumerable.Range('a', 26).Select(i => (Char)i).ToArray();
                int k;
                Random rand = new Random();
                for (int i = 0; i < size; i++)
                {
                    for (int j = 1; j < size + 1; j++)
                    {
                        //select index from the array
                        k = (int)(rand.NextDouble() * tempCards.Count);
                        //add card
                        cards.Add(Char.ToString(az[i]).ToUpper() + j, tempCards.ElementAt(k));
                        Console.Write(Char.ToString(az[i]).ToUpper() + j + "(" + tempCards.ElementAt(k).Id + ") ");
                        //remove card from temp list
                        tempCards.RemoveAt(k);
                    }
                    Console.WriteLine("");
                }

                return true;
            }
            return false;
        }
    }
}
